package com.example.resource;

import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Slf4j
@Path("/start/get")
public class GetExampleResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/emptyParam")
    public String emptyParam() {
        return "Hello from Quarkus REST";
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/queryParam")
    public String queryParam(@QueryParam("name") String name) {
        return "Hello from Quarkus REST , QueryParam name = " + name;
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/pathParam/{name}")
    public String hello3(@PathParam("name") String name) {
        return "Hello from Quarkus REST , PathParam name = " + name;
    }

    /**
     * 测试全局异常处理
     */
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/exception")
    public String exception() {
        throw new RuntimeException("test global exception");
    }

    /**
     * 下载功能
     * @return 返回结果
     */
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    @Path("/download")
    public Response download() {
        String resource = Objects.requireNonNull(this.getClass().getResource("")).getPath();
        File file = new File(resource + "/PostExampleResource.class");

        //对输出的文件名进行编码，防止下载的中文文件名乱码
        String encodeFileName = URLEncoder.encode("自定义文件名.txt", StandardCharsets.UTF_8);

        return Response.ok(file)
                .header("content-disposition", "attachment; filename=\"" + encodeFileName + "\"")
                .header("Content-Length", file.length())
                .build();

    }
}
